#!/bin/bash

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        return 1
    fi
    return 0
}

# 检测操作系统
detect_os() {
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # 检查是否是 Amazon Linux
        if [[ -f /etc/os-release ]]; then
            . /etc/os-release
            if [[ "$ID" == "amzn" ]]; then
                OS="amazonlinux"
                # Amazon Linux 2023 使用 dnf，Amazon Linux 2 使用 yum
                if [[ "$VERSION_ID" == "2023" ]] || command -v dnf &> /dev/null; then
                    PACKAGE_MANAGER="dnf"
                else
                    PACKAGE_MANAGER="yum"
                fi
            elif command -v apt-get &> /dev/null; then
                OS="ubuntu"
                PACKAGE_MANAGER="apt"
            elif command -v dnf &> /dev/null; then
                OS="fedora"
                PACKAGE_MANAGER="dnf"
            elif command -v yum &> /dev/null; then
                OS="centos"
                PACKAGE_MANAGER="yum"
            else
                OS="linux"
                PACKAGE_MANAGER="unknown"
            fi
        else
            OS="linux"
            PACKAGE_MANAGER="unknown"
        fi
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
        PACKAGE_MANAGER="brew"
    else
        OS="unknown"
        PACKAGE_MANAGER="unknown"
    fi
    
    # 检测架构
    ARCH=$(uname -m)
    case $ARCH in
        x86_64)
            ARCH="amd64"
            ;;
        aarch64|arm64)
            ARCH="arm64"
            ;;
        *)
            ARCH="amd64"
            ;;
    esac
}

# 安装 kubectl
install_kubectl() {
    log_info "安装 kubectl..."
    
    case $OS in
        ubuntu)
            curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/$ARCH/kubectl"
            sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
            rm kubectl
            ;;
        amazonlinux|centos|fedora)
            curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/$ARCH/kubectl"
            sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl
            rm kubectl
            ;;
        macos)
            if command -v brew &> /dev/null; then
                brew install kubectl
            else
                curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/darwin/$ARCH/kubectl"
                chmod +x kubectl
                sudo mv kubectl /usr/local/bin/
            fi
            ;;
        *)
            log_error "不支持的操作系统，请手动安装 kubectl"
            exit 1
            ;;
    esac
    
    log_success "kubectl 安装完成"
}

# 安装 helm
install_helm() {
    log_info "安装 helm..."
    
    case $OS in
        ubuntu)
            curl https://baltocdn.com/helm/signing.asc | gpg --dearmor | sudo tee /usr/share/keyrings/helm.gpg > /dev/null
            echo "deb [arch=$ARCH signed-by=/usr/share/keyrings/helm.gpg] https://baltocdn.com/helm/stable/debian/ all main" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list
            sudo apt-get update
            sudo apt-get install helm -y
            ;;
        amazonlinux)
            # Amazon Linux 2023 推荐使用官方脚本安装
            curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
            chmod 700 get_helm.sh
            ./get_helm.sh
            rm get_helm.sh
            ;;
        centos)
            curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
            chmod 700 get_helm.sh
            ./get_helm.sh
            rm get_helm.sh
            ;;
        fedora)
            sudo dnf install helm -y
            ;;
        macos)
            if command -v brew &> /dev/null; then
                brew install helm
            else
                curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
                chmod 700 get_helm.sh
                ./get_helm.sh
                rm get_helm.sh
            fi
            ;;
        *)
            curl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3
            chmod 700 get_helm.sh
            ./get_helm.sh
            rm get_helm.sh
            ;;
    esac
    
    log_success "helm 安装完成"
}

# 安装 AWS CLI
install_aws_cli() {
    log_info "安装 AWS CLI..."
    
    case $OS in
        ubuntu)
            sudo apt-get update
            sudo apt-get install awscli -y
            # 如果版本太旧，使用官方安装方法
            if ! aws --version | grep -q "aws-cli/2"; then
                curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
                unzip awscliv2.zip
                sudo ./aws/install --update
                rm -rf awscliv2.zip aws/
            fi
            ;;
        amazonlinux)
            # Amazon Linux 2023 通常预装了 AWS CLI v2
            if ! check_command "aws"; then
                if [[ "$PACKAGE_MANAGER" == "dnf" ]]; then
                    sudo dnf install awscli2 -y
                else
                    sudo yum install awscli -y
                fi
            fi
            
            # 检查版本，如果是 v1 则升级到 v2
            if ! aws --version | grep -q "aws-cli/2"; then
                log_info "升级到 AWS CLI v2..."
                curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
                unzip awscliv2.zip
                sudo ./aws/install --update
                rm -rf awscliv2.zip aws/
            fi
            ;;
        centos|fedora)
            curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
            unzip awscliv2.zip
            sudo ./aws/install
            rm -rf awscliv2.zip aws/
            ;;
        macos)
            if command -v brew &> /dev/null; then
                brew install awscli
            else
                curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
                sudo installer -pkg AWSCLIV2.pkg -target /
                rm AWSCLIV2.pkg
            fi
            ;;
        *)
            log_error "不支持的操作系统，请手动安装 AWS CLI"
            exit 1
            ;;
    esac
    
    log_success "AWS CLI 安装完成"
}

# 安装 eksctl
install_eksctl() {
    log_info "安装 eksctl..."
    
    case $OS in
        amazonlinux|ubuntu|centos|fedora)
            curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_$ARCH.tar.gz" | tar xz -C /tmp
            sudo mv /tmp/eksctl /usr/local/bin
            ;;
        macos)
            if command -v brew &> /dev/null; then
                brew tap weaveworks/tap
                brew install weaveworks/tap/eksctl
            else
                curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_$ARCH.tar.gz" | tar xz -C /tmp
                sudo mv /tmp/eksctl /usr/local/bin
            fi
            ;;
        *)
            curl --silent --location "https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_$ARCH.tar.gz" | tar xz -C /tmp
            sudo mv /tmp/eksctl /usr/local/bin
            ;;
    esac
    
    log_success "eksctl 安装完成"
}

# 配置 AWS CLI
configure_aws_cli() {
    log_info "检查 AWS CLI 配置..."
    
    if ! aws sts get-caller-identity &> /dev/null; then
        log_warning "AWS CLI 未配置或配置无效"
        echo
        log_info "请配置 AWS CLI："
        echo "选择配置方式："
        echo "1. 使用 aws configure (推荐)"
        echo "2. 使用环境变量"
        echo "3. 使用 IAM 角色 (EC2/Lambda 等)"
        echo "4. 跳过配置 (如果已通过其他方式配置)"
        echo
        
        read -p "请选择 (1-4): " aws_config_choice
        
        case $aws_config_choice in
            1)
                log_info "请输入 AWS 凭证信息："
                aws configure
                ;;
            2)
                log_info "请设置以下环境变量："
                echo "export AWS_ACCESS_KEY_ID=your_access_key"
                echo "export AWS_SECRET_ACCESS_KEY=your_secret_key"
                echo "export AWS_DEFAULT_REGION=your_region"
                echo
                read -p "设置完成后按 Enter 继续..."
                ;;
            3)
                log_info "假设您正在使用 IAM 角色，继续执行..."
                ;;
            4)
                log_info "跳过 AWS CLI 配置"
                ;;
            *)
                log_error "无效选择"
                exit 1
                ;;
        esac
        
        # 重新检查
        if ! aws sts get-caller-identity &> /dev/null; then
            log_error "AWS CLI 配置验证失败，请检查配置"
            exit 1
        fi
    fi
    
    log_success "AWS CLI 配置验证通过"
}

# 配置 kubectl
configure_kubectl() {
    log_info "配置 kubectl 连接到 EKS 集群..."
    
    if [[ -z "$CLUSTER_NAME" || -z "$AWS_REGION" ]]; then
        log_error "集群名称和区域信息缺失"
        exit 1
    fi
    
    # 更新 kubeconfig
    aws eks update-kubeconfig --region $AWS_REGION --name $CLUSTER_NAME
    
    # 验证连接
    if ! kubectl cluster-info &> /dev/null; then
        log_error "无法连接到 Kubernetes 集群 $CLUSTER_NAME"
        log_info "请检查："
        echo "  - 集群名称是否正确: $CLUSTER_NAME"
        echo "  - AWS 区域是否正确: $AWS_REGION"
        echo "  - AWS 凭证是否有访问 EKS 的权限"
        echo "  - 集群是否存在且处于 ACTIVE 状态"
        exit 1
    fi
    
    log_success "kubectl 已成功连接到集群 $CLUSTER_NAME"
}

# 检查并创建 OIDC 提供者
check_and_create_oidc_provider() {
    log_info "检查 OIDC 提供者..."
    
    # 获取集群的 OIDC Issuer URL
    OIDC_ISSUER=$(aws eks describe-cluster --name $CLUSTER_NAME --region $AWS_REGION --query "cluster.identity.oidc.issuer" --output text 2>/dev/null)
    
    if [[ -z "$OIDC_ISSUER" || "$OIDC_ISSUER" == "None" ]]; then
        log_error "无法获取集群的 OIDC Issuer URL，请检查集群状态"
        exit 1
    fi
    
    # 提取 OIDC ID
    OIDC_ID=$(echo $OIDC_ISSUER | cut -d '/' -f 5)
    
    # 检查是否已存在 OIDC 提供者
    log_info "检查是否存在 OIDC 提供者: $OIDC_ID"
    
    if ! aws iam list-open-id-connect-providers --query "OpenIDConnectProviderList[?ends_with(Arn, '$OIDC_ID')]" --output text | grep -q "$OIDC_ID"; then
        log_warning "OIDC 提供者不存在，正在创建..."
        
        # 使用 eksctl 创建 OIDC 提供者
        log_info "运行: eksctl utils associate-iam-oidc-provider --region=$AWS_REGION --cluster=$CLUSTER_NAME --approve"
        
        if eksctl utils associate-iam-oidc-provider --region=$AWS_REGION --cluster=$CLUSTER_NAME --approve; then
            log_success "OIDC 提供者创建成功"
            
            # 等待一下确保提供者完全创建
            log_info "等待 OIDC 提供者完全生效..."
            sleep 10
        else
            log_error "OIDC 提供者创建失败"
            log_info "您可以手动运行以下命令："
            echo "eksctl utils associate-iam-oidc-provider --region=$AWS_REGION --cluster=$CLUSTER_NAME --approve"
            exit 1
        fi
    else
        log_success "OIDC 提供者已存在"
    fi
    
    # 再次验证
    if aws iam list-open-id-connect-providers --query "OpenIDConnectProviderList[?ends_with(Arn, '$OIDC_ID')]" --output text | grep -q "$OIDC_ID"; then
        log_success "OIDC 提供者验证通过"
        echo "  OIDC Issuer: $OIDC_ISSUER"
        echo "  OIDC ID: $OIDC_ID"
    else
        log_error "OIDC 提供者验证失败"
        exit 1
    fi
}


# 验证输入参数
validate_inputs() {
    if [[ -z "$CLUSTER_NAME" ]]; then
        log_error "集群名称不能为空"
        exit 1
    fi
    
    if [[ -z "$AWS_REGION" ]]; then
        log_error "AWS 区域不能为空"
        exit 1
    fi
    
    if [[ -z "$EFS_ID" ]]; then
        log_error "EFS 文件系统 ID 不能为空"
        exit 1
    fi
}

# 获取用户输入
get_user_inputs() {
    log_info "=== AWS Load Balancer Controller & EFS CSI 安装脚本 ==="
    echo
    
    # EKS 集群信息 (需要在配置 kubectl 之前获取)
    echo
    log_info "=== EKS 集群配置 ==="
    
    # 检查是否已有集群连接
    current_context=$(kubectl config current-context 2>/dev/null || echo "")
    if [[ -n "$current_context" ]]; then
        log_info "当前 kubectl 上下文: $current_context"
        read -p "是否使用当前集群? (y/n): " use_current
        if [[ "$use_current" == "y" || "$use_current" == "Y" ]]; then
            # 从当前上下文获取集群信息
            CLUSTER_NAME=$(echo $current_context | cut -d'/' -f2 2>/dev/null || echo "")
            AWS_REGION=$(echo $current_context | cut -d':' -f4 2>/dev/null || echo "")
            
            if [[ -z "$CLUSTER_NAME" || -z "$AWS_REGION" ]]; then
                log_warning "无法从当前上下文获取完整集群信息，请手动输入"
                read -p "请输入 EKS 集群名称: " CLUSTER_NAME
                read -p "请输入 AWS 区域 (例: us-west-2): " AWS_REGION
            else
                log_info "检测到集群: $CLUSTER_NAME (区域: $AWS_REGION)"
            fi
        else
            read -p "请输入 EKS 集群名称: " CLUSTER_NAME
            read -p "请输入 AWS 区域 (例: us-west-2): " AWS_REGION
        fi
    else
        read -p "请输入 EKS 集群名称: " CLUSTER_NAME
        read -p "请输入 AWS 区域 (例: us-west-2): " AWS_REGION
    fi
    
    # EFS 信息
    read -p "请输入 EFS 文件系统 ID (例: fs-xxxxxxxxx): " EFS_ID
    read -p "请输入 EFS StorageClass 名称 [默认: efs-sc]: " EFS_STORAGE_CLASS
    EFS_STORAGE_CLASS=${EFS_STORAGE_CLASS:-efs-sc}
    
    # 可选配置
    read -p "是否安装 AWS Load Balancer Controller? (y/n) [默认: y]: " INSTALL_LB_CONTROLLER
    INSTALL_LB_CONTROLLER=${INSTALL_LB_CONTROLLER:-y}
    
    read -p "是否安装 EFS CSI 驱动? (y/n) [默认: y]: " INSTALL_EFS_CSI
    INSTALL_EFS_CSI=${INSTALL_EFS_CSI:-y}
    
    # Helm repository URL (可选自定义)
    HELM_REPO_EKS="https://aws.github.io/eks-charts"
    HELM_REPO_EFS="https://kubernetes-sigs.github.io/aws-efs-csi-driver"
    
    echo
    log_info "配置确认:"
    echo "  集群名称: $CLUSTER_NAME"
    echo "  AWS 区域: $AWS_REGION"
    echo "  EFS ID: $EFS_ID"
    echo "  EFS StorageClass: $EFS_STORAGE_CLASS"
    echo "  安装 LB Controller: $INSTALL_LB_CONTROLLER"
    echo "  安装 EFS CSI: $INSTALL_EFS_CSI"
    echo
    
    read -p "确认继续安装? (y/n): " CONFIRM
    if [[ "$CONFIRM" != "y" && "$CONFIRM" != "Y" ]]; then
        log_warning "安装已取消"
        exit 0
    fi
}

# 检查和安装必要工具
check_and_install_prerequisites() {
    log_info "检查和安装必要工具..."
    
    # 检测操作系统
    detect_os
    log_info "检测到操作系统: $OS ($ARCH)"
    
    # 检查和安装各个工具
    local tools_to_install=()
    
    if ! check_command "curl"; then
        case $OS in
            ubuntu)
                sudo apt-get update && sudo apt-get install curl -y
                ;;
            amazonlinux)
                if [[ "$PACKAGE_MANAGER" == "dnf" ]]; then
                    sudo dnf install curl unzip tar gzip -y
                else
                    sudo yum install curl unzip tar gzip -y
                fi
                ;;
            centos|fedora)
                if [[ "$PACKAGE_MANAGER" == "dnf" ]]; then
                    sudo dnf install curl -y
                else
                    sudo yum install curl -y
                fi
                ;;
            macos)
                if command -v brew &> /dev/null; then
                    brew install curl
                else
                    log_error "请先安装 Homebrew 或手动安装 curl"
                    exit 1
                fi
                ;;
        esac
    fi
    
    if ! check_command "kubectl"; then
        tools_to_install+=("kubectl")
    fi
    
    if ! check_command "helm"; then
        tools_to_install+=("helm")
    fi
    
    if ! check_command "aws"; then
        tools_to_install+=("aws")
    fi
    
    if ! check_command "eksctl"; then
        tools_to_install+=("eksctl")
    fi
    
    if ! check_command "unzip"; then
        case $OS in
            ubuntu)
                sudo apt-get update && sudo apt-get install unzip -y
                ;;
            amazonlinux)
                if [[ "$PACKAGE_MANAGER" == "dnf" ]]; then
                    sudo dnf install unzip -y
                else
                    sudo yum install unzip -y
                fi
                ;;
            centos|fedora)
                if [[ "$PACKAGE_MANAGER" == "dnf" ]]; then
                    sudo dnf install unzip -y
                else
                    sudo yum install unzip -y
                fi
                ;;
            macos)
                # macOS 通常自带 unzip
                ;;
        esac
    fi
    
    # 安装缺失的工具
    for tool in "${tools_to_install[@]}"; do
        case $tool in
            kubectl)
                install_kubectl
                ;;
            helm)
                install_helm
                ;;
            aws)
                install_aws_cli
                ;;
            eksctl)
                install_eksctl
                ;;
        esac
    done
    
    # 配置 AWS CLI
    configure_aws_cli
    
    # 配置 kubectl (在获取集群信息后调用)
    
    log_success "必要工具检查和安装完成"
    
    # 显示工具版本
    log_info "已安装工具版本："
    kubectl version --client --short 2>/dev/null || kubectl version --client 2>/dev/null
    helm version --short 2>/dev/null || helm version 2>/dev/null
    aws --version
    eksctl version
}

# 获取集群信息
get_cluster_info() {
    log_info "获取集群信息..."
    
    # 获取 AWS Account ID
    AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
    if [[ -z "$AWS_ACCOUNT_ID" ]]; then
        log_error "无法获取 AWS Account ID"
        exit 1
    fi
    
    # 获取 OIDC Issuer URL
    OIDC_ISSUER=$(aws eks describe-cluster --name $CLUSTER_NAME --region $AWS_REGION --query "cluster.identity.oidc.issuer" --output text)
    if [[ -z "$OIDC_ISSUER" ]]; then
        log_error "无法获取 OIDC Issuer URL"
        exit 1
    fi
    
    OIDC_ID=$(echo $OIDC_ISSUER | cut -d '/' -f 5)
    
    log_success "集群信息获取完成"
    echo "  Account ID: $AWS_ACCOUNT_ID"
    echo "  OIDC Issuer: $OIDC_ISSUER"
    echo "  OIDC ID: $OIDC_ID"
}

# 安装 AWS Load Balancer Controller
install_lb_controller() {
    if [[ "$INSTALL_LB_CONTROLLER" != "y" && "$INSTALL_LB_CONTROLLER" != "Y" ]]; then
        log_info "跳过 AWS Load Balancer Controller 安装"
        return
    fi
    
    log_info "开始安装 AWS Load Balancer Controller..."
    
    # 创建 IAM 策略
    log_info "创建 IAM 策略..."
    curl -s https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.7.2/docs/install/iam_policy.json -o /tmp/iam_policy.json
    
    aws iam create-policy \
        --policy-name AWSLoadBalancerControllerIAMPolicy \
        --policy-document file:///tmp/iam_policy.json \
        --region $AWS_REGION 2>/dev/null || log_warning "IAM 策略可能已存在"
    
    # 创建 IAM 角色和服务账户
    log_info "创建 IAM 角色和服务账户..."
    eksctl create iamserviceaccount \
        --cluster=$CLUSTER_NAME \
        --region=$AWS_REGION \
        --namespace=kube-system \
        --name=aws-load-balancer-controller \
        --role-name AmazonEKSLoadBalancerControllerRole \
        --attach-policy-arn=arn:aws-cn:iam::$AWS_ACCOUNT_ID:policy/AWSLoadBalancerControllerIAMPolicy \
        --approve 2>/dev/null || log_warning "服务账户可能已存在"
    
    # 添加 Helm repository
    log_info "添加 Helm repository..."
    helm repo add eks $HELM_REPO_EKS
    helm repo update
    
    
    # 安装 AWS Load Balancer Controller
    log_info "安装 AWS Load Balancer Controller..."
    helm upgrade --install aws-load-balancer-controller eks/aws-load-balancer-controller \
        -n kube-system \
        --set clusterName=$CLUSTER_NAME \
        --set serviceAccount.create=false \
        --set serviceAccount.name=aws-load-balancer-controller \
        --set region=$AWS_REGION \
        --set vpcId=$(aws eks describe-cluster --name $CLUSTER_NAME --region $AWS_REGION --query "cluster.resourcesVpcConfig.vpcId" --output text)
    
    # 等待部署完成
    log_info "等待 AWS Load Balancer Controller 部署完成..."
    kubectl wait --for=condition=ready pod -l app.kubernetes.io/name=aws-load-balancer-controller -n kube-system --timeout=300s
    
    log_success "AWS Load Balancer Controller 安装完成"
}

# 安装 EFS CSI 驱动
install_efs_csi() {
    if [[ "$INSTALL_EFS_CSI" != "y" && "$INSTALL_EFS_CSI" != "Y" ]]; then
        log_info "跳过 EFS CSI 驱动安装"
        return
    fi
    
    log_info "开始安装 EFS CSI 驱动..."
    
    # 创建 IAM 角色和服务账户
    log_info "创建 EFS CSI 驱动的 IAM 角色..."
    eksctl create iamserviceaccount \
        --cluster $CLUSTER_NAME \
        --region $AWS_REGION \
        --namespace kube-system \
        --name efs-csi-controller-sa \
        --attach-policy-arn arn:aws-cn:iam::aws:policy/service-role/AmazonEFSCSIDriverPolicy \
        --approve 2>/dev/null || log_warning "EFS CSI 服务账户可能已存在"
    
    # 添加 Helm repository
    log_info "添加 EFS CSI Helm repository..."
    helm repo add aws-efs-csi-driver $HELM_REPO_EFS
    helm repo update
    
    # 安装 EFS CSI 驱动
    log_info "安装 EFS CSI 驱动..."
    helm upgrade --install aws-efs-csi-driver aws-efs-csi-driver/aws-efs-csi-driver \
        --namespace kube-system \
        --set controller.serviceAccount.create=false \
        --set controller.serviceAccount.name=efs-csi-controller-sa
    
    # 等待部署完成
    log_info "等待 EFS CSI 驱动部署完成..."
    kubectl wait --for=condition=ready pod -l app=efs-csi-controller -n kube-system --timeout=300s
    
    log_success "EFS CSI 驱动安装完成"
}

# 创建 EFS StorageClass
create_efs_storageclass() {
    if [[ "$INSTALL_EFS_CSI" != "y" && "$INSTALL_EFS_CSI" != "Y" ]]; then
        log_info "跳过 EFS StorageClass 创建"
        return
    fi
    
    log_info "创建 EFS StorageClass..."
    
    cat <<EOF | kubectl apply -f -
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
  name: $EFS_STORAGE_CLASS
provisioner: efs.csi.aws.com
parameters:
  provisioningMode: efs-ap
  fileSystemId: $EFS_ID
  directoryPerms: "0755"
  gidRangeStart: "1000"
  gidRangeEnd: "2000"
  basePath: "/dynamic_provisioning"
volumeBindingMode: Immediate
allowVolumeExpansion: true
EOF
    
    log_success "EFS StorageClass '$EFS_STORAGE_CLASS' 创建完成"
}

# 验证安装
verify_installation() {
    log_info "验证安装状态..."
    
    echo
    log_info "=== 验证结果 ==="
    
    if [[ "$INSTALL_LB_CONTROLLER" == "y" || "$INSTALL_LB_CONTROLLER" == "Y" ]]; then
        echo
        log_info "AWS Load Balancer Controller 状态:"
        kubectl get pods -n kube-system -l app.kubernetes.io/name=aws-load-balancer-controller
    fi
    
    if [[ "$INSTALL_EFS_CSI" == "y" || "$INSTALL_EFS_CSI" == "Y" ]]; then
        echo
        log_info "EFS CSI 驱动状态:"
        kubectl get pods -n kube-system -l app=efs-csi-controller
        
        echo
        log_info "EFS StorageClass:"
        kubectl get storageclass $EFS_STORAGE_CLASS 2>/dev/null || log_warning "StorageClass 未找到"
    fi
}

# 创建测试 PVC 示例
create_test_example() {
    if [[ "$INSTALL_EFS_CSI" != "y" && "$INSTALL_EFS_CSI" != "Y" ]]; then
        return
    fi
    
    log_info "创建测试 PVC 示例文件..."
    
    cat > /tmp/efs-test-pvc.yaml <<EOF
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: efs-test-pvc
  namespace: default
spec:
  accessModes:
    - ReadWriteMany
  storageClassName: $EFS_STORAGE_CLASS
  resources:
    requests:
      storage: 5Gi
---
apiVersion: v1
kind: Pod
metadata:
  name: efs-test-pod
  namespace: default
spec:
  containers:
  - name: app
    image: nginx:latest
    volumeMounts:
    - name: efs-storage
      mountPath: /data
    command: ["/bin/sh"]
    args: ["-c", "echo 'Hello EFS!' > /data/test.txt && tail -f /dev/null"]
  volumes:
  - name: efs-storage
    persistentVolumeClaim:
      claimName: efs-test-pvc
EOF
    
    log_info "测试文件已创建: /tmp/efs-test-pvc.yaml"
    log_info "要测试 EFS，请运行: kubectl apply -f /tmp/efs-test-pvc.yaml"
}

# 清理函数
cleanup() {
    log_info "清理临时文件..."
    rm -f /tmp/iam_policy.json /tmp/efs-test-pvc.yaml
}

# 主函数
main() {
    # 设置清理陷阱
    trap cleanup EXIT
    
    # 获取用户输入
    get_user_inputs
    
    # 验证输入
    validate_inputs
    
    # 检查先决条件并安装必要工具
    check_and_install_prerequisites
    
    # 配置 kubectl 连接到集群
    configure_kubectl
    
    # 获取集群信息
    get_cluster_info

    #配置OIDC
    check_and_create_oidc_provider
    
    # 安装组件
    install_lb_controller
    install_efs_csi
    create_efs_storageclass
    
    # 验证安装
    verify_installation
    
    # 创建测试示例
    create_test_example
    
    echo
    log_success "=== 安装完成 ==="
    log_info "所有组件已成功安装并配置完成！"
    
    if [[ "$INSTALL_EFS_CSI" == "y" || "$INSTALL_EFS_CSI" == "Y" ]]; then
        echo
        log_info "EFS 使用提示:"
        echo "  - StorageClass 名称: $EFS_STORAGE_CLASS"
        echo "  - EFS 文件系统 ID: $EFS_ID"
        echo "  - 测试文件: /tmp/efs-test-pvc.yaml"
        echo "  - 使用示例: kubectl apply -f /tmp/efs-test-pvc.yaml"
    fi
}

# 检查是否直接运行脚本
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi